package com.lyn.seckill.service.impl;

import com.lyn.seckill.common.error.BusinessException;
import com.lyn.seckill.common.error.EnumBusinessError;
import com.lyn.seckill.dao.OrderInfoDoMapper;
import com.lyn.seckill.dao.SequenceInfoDoMapper;
import com.lyn.seckill.dataobject.OrderInfoDo;
import com.lyn.seckill.dataobject.SequenceInfoDo;
import com.lyn.seckill.service.ItemService;
import com.lyn.seckill.service.OrderService;
import com.lyn.seckill.service.UserService;
import com.lyn.seckill.service.model.ItemModel;
import com.lyn.seckill.service.model.OrderModel;
import com.lyn.seckill.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OrderServiceImpl implements OrderService {

    private final ItemService itemService;
    private final UserService userService;
    private final OrderInfoDoMapper orderInfoDoMapper;
    private final SequenceInfoDoMapper sequenceInfoDoMapper;
    public OrderServiceImpl(ItemService itemService, UserService userService, OrderInfoDoMapper orderInfoDoMapper, SequenceInfoDoMapper sequenceInfoDoMapper) {
        this.itemService = itemService;
        this.userService = userService;
        this.orderInfoDoMapper = orderInfoDoMapper;
        this.sequenceInfoDoMapper = sequenceInfoDoMapper;
    }

    @Override
    @Transactional
    public OrderModel createOrder(Integer userId, Integer itemId, Integer amount, Integer promoId) throws BusinessException {
        // 校验下单状态，商品是否存在，用户是否合法，数量是否正确
        ItemModel itemById = itemService.getItemById(itemId);
        if (itemById == null) {
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"商品信息不存在");
        }
        UserModel userById = userService.getUserById(userId);
        if (userById == null) {
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"用户信息不存在");
        }
        if (amount <=0 || amount > itemById.getStock()) {
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"购买数量错误");
        }
        // 校验活动ID的状态
        if (promoId != null) {
            // 1、校验对应活动是否存在这个使用商品
            if (promoId.intValue() != itemById.getPromoModel().getId()) {
                throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"活动信息不正确");
            } else if (itemById.getPromoModel().getStatus().intValue() != EnumBusinessError.PROMO_ON_GOING) {
                // 2、校验活动是否正在进行中
                throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"活动尚未开始");
            }
        }

        // 订单生成后，库存扣减
        boolean b = itemService.decreaseStock(itemId, amount);
        if (!b) {
            throw new BusinessException(EnumBusinessError.STOCK_NOT_ENOUGH);
        }
        // 订单入库
        OrderModel orderModel = new OrderModel();
        orderModel.setUserId(userId);
        orderModel.setItemId(itemId);
        orderModel.setAmount(amount);
        // 根据活动状态，改变商品价格
        BigDecimal price = new BigDecimal(0);
        if (promoId != null) {
            price = itemById.getPromoModel().getPromoItemPrice();
        } else {
            price = itemById.getPrice();
        }
        orderModel.setPromoId(promoId);
        orderModel.setItemPrice(price);
        orderModel.setOrderPrice(price.multiply(BigDecimal.valueOf(amount)));

        // 生成交易流水号，订单号
        orderModel.setId(this.generatorOrderNo(userId));
        OrderInfoDo orderInfoDo = this.convertFromOrderModel(orderModel);
        orderInfoDoMapper.insertSelective(orderInfoDo);
        itemService.increaseSales(itemId,amount);
        // 返回
        return orderModel;
    }


    private OrderInfoDo convertFromOrderModel(OrderModel orderModel) {
        if (orderModel == null) {
            return null;
        }
        OrderInfoDo orderInfoDo = new OrderInfoDo();
        BeanUtils.copyProperties(orderModel,orderInfoDo);
        orderInfoDo.setItemPrice(orderModel.getItemPrice().doubleValue());
        orderInfoDo.setOrderPrice(orderModel.getOrderPrice().doubleValue());
        return orderInfoDo;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String generatorOrderNo(Integer userId) {
        // 订单号有16位
        StringBuilder sb = new StringBuilder(16);
        // 前8位为时间信息，年月日
        LocalDateTime now = LocalDateTime.now();
        String pre8 = now.format(DateTimeFormatter.ISO_DATE).replace("-", "");
        sb.append(pre8);
        // 中间6位为自增序列
        int sequence = 0;
        SequenceInfoDo order_info = sequenceInfoDoMapper.getSequenceByName("order_info");
        sequence = order_info.getCurrentValue();
        order_info.setCurrentValue(order_info.getCurrentValue() + order_info.getStep());
        sequenceInfoDoMapper.updateByPrimaryKeySelective(order_info);
        String s = String.valueOf(sequence);
        if (s.length() > 6) {
            s = s.substring(0, 6);
        } else {
            for (int i = 0; i < (6 - s.length()); i++) {
                sb.append(0);
            }
        }
        sb.append(s);
        // 最后2位为分库分表位
        int suf2 = userId % 100;
        sb.append(suf2 > 9 ? suf2 : ("0" + suf2));
        return sb.toString();
    }
}
